package org.buptsse.thread;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.entity.FilterResultItem;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.HttpHelper;
import org.buptsse.utils.JsonUtils;

import com.google.gson.reflect.TypeToken;

import android.R.integer;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class FindSellByFilterThread extends Thread {

	private Context context;
	private Handler handler;
	private String username,school,condition,keywords;
	private int price;
	
	public FindSellByFilterThread(Context context,Handler handler,
								  String username,String school,
								  String condition, String keyword,
								  int price)
	{
		this.context=context;
		this.handler=handler;
		this.username=username;
		this.school=school;
		this.condition=condition;
		this.keywords=keyword;
		this.price=price;
	}
	
	public void run()
	{
		if(ConnectionChecker.CheckConnection(context, handler)==false)
		{
			return;
		}
		ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("username", username));
		param.add(new BasicNameValuePair("price", new Integer(price).toString()));
		if(condition!=null && !condition.equals(""))
		{
			param.add(new BasicNameValuePair("quality", condition));
		}
		if(school!=null && !school.equals("不限"))
		{
			param.add(new BasicNameValuePair("sellerschool", school));
		}
		if(keywords!=null && !keywords.equals(""))
		{
			param.add(new BasicNameValuePair("keywords", keywords));
		}
		try {
			String json=HttpHelper.sendPost(APPConstant.findSellByFilterUrl, param);
			System.out.println("json is:"+json);
			if(!json.contains("failure"))
			{
				//成功
				LinkedList<FilterResultItem> list=(LinkedList<FilterResultItem>) JsonUtils.getJsonObject(json, new TypeToken<LinkedList<FilterResultItem>>() {}.getType());
				Message msg=handler.obtainMessage(APPConstant.findSellByFilterFinish);
				msg.obj=list;
				handler.sendMessage(msg);
				return;
			}else {
				//失败
				Message msg=handler.obtainMessage(APPConstant.findSellByFilterError);
				handler.sendMessage(msg);
				return;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
